
"""
ftp文件服务器服务端
"""
from socket import *
from threading import Thread
from time import sleep
import os
filedir="D:\\Python人工智能\\mouth02\\day_09\\new_files\\"
class Server(Thread):
    def __init__(self,cnn):
        self.cnn=cnn
        super().__init__()
    def run(self):
        while True:
            request = self.cnn.recv(1024)
            tmp=request.decode().splite(' ',3)
            if not request or tmp[0]=="Quit":
                break
            elif request=="List":
                self.do_list()
            elif tmp[0]=="Get":
                self.do_get(tmp[1])
            elif tmp[0]=="Put":
                self.do_put(tmp[1])
        self.cnn.close()
    def do_list(self):
        files=os.listdir(filedir)
        if files:
            self.cnn.send(b"OK")
            sleep(0.1)                 #防止粘黏
            data="\n".join(files)
            self.cnn.send(data)
            sleep(0.1)
            self.cnn.send(b"##")
        else:
            self.cnn.send(b"EMPTY")

    def do_get(self,filename):
        try:
            fr=open(filedir+filename,"rb")
        except:
            self.cnn.send(b"FAIL")
        else:
            self.cnn.send(b"OK")
            sleep(0.1)
            while True:
                data=fr.read(1024)
                if not data:
                    break
                self.cnn.send(data)
            sleep(0.1)
            self.cnn.send(b"##")

    def do_put(self,filename):
        if os.path.exists(filedir+filename):
            self.cnn.send(b"EXIT")
        else:
            self.cnn.send(b"OK")
            sleep(0.1)
            while True:
                data=self.cnn.recv(1024)
                fw = open(filename, "wb")
                if data==b'##':
                    break

                fw.write(data)
            fw.close()
            self.cnn.close()

class Main():
    def __init__(self, host=None, port=None):
        # 服务器端地址
        self.host = host
        self.port = port
        self.addr = (host, port)
        self.sock=self.create_sock()

    def create_sock(self):
        sock=socket()
        sock.bind(self.addr)
        return sock

    #循环连接客户端
    def server_forerver(self):
        self.sock.listen(10)
        print("listen the port %d" %self.port)
        while True:
            # try:
            cnn,addr=self.sock.accept()
            print("connect from",addr)
            ser=Server(cnn)
            ser.start()

if __name__ == '__main__':

    Main('0.0.0.0',8888).server_forerver()